<template>
  <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" size="large">
    <el-form-item prop="username">
      <el-input v-model="loginForm.username" placeholder="用户名：admin / user">
        <template #prefix>
          <el-icon class="el-input__icon">
            <user />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input v-model="loginForm.password" type="password" placeholder="密码：123456" show-password
        autocomplete="new-password">
        <template #prefix>
          <el-icon class="el-input__icon">
            <lock />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
  </el-form>
  <div class="base_other">
    <div>{{ $t("login.otherAccountTip") }}</div>
    <div>
      <el-switch v-model="language" inline-prompt style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
        active-text="zhCn" inactive-text="RU" @change="langChange" />
    </div>
  </div>
  <div class="login-btn">
    <el-button :icon="CircleClose" round size="large" @click="resetForm(loginFormRef)"> 重置 </el-button>
    <el-button :icon="UserFilled" round size="large" type="primary" :loading="loading" @click="login(loginFormRef)">
      {{ $t("login.loginTxt") }}
    </el-button>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, computed, onMounted, getCurrentInstance } from "vue";
  import { useRouter } from "vue-router";
  import { HOME_URL } from "@/config";
  import { getTimeState } from "@/utils";
  import { Login } from "@/api/interface";
  import { ElNotification } from "element-plus";
  import { loginApi } from "@/api/modules/login";
  import { useUserStore } from "@/stores/modules/user";
  import { useTabsStore } from "@/stores/modules/tabs";
	import { getAlltree } from "@/minxins/useOrgsStore";//获取组织架构树
  import { useKeepAliveStore } from "@/stores/modules/keepAlive";
  import { initDynamicRouter } from "@/routers/modules/dynamicRouter";
  import { CircleClose, UserFilled } from "@element-plus/icons-vue";
  import type { ElForm } from "element-plus";
  import { ElMessage } from "element-plus";
  import { useI18n } from "vue-i18n";
  import { useGlobalStore } from "@/stores/modules/global";
  import { LanguageType } from "@/stores/interface";

  const i18n = useI18n();
  const globalStore = useGlobalStore();
  const { proxy } = getCurrentInstance();
  const router = useRouter();
  const userStore = useUserStore();
  const tabsStore = useTabsStore(); 
  const keepAliveStore = useKeepAliveStore();
  const isSafari = ref(false);
  isSafari.value = /Safari/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent);
  type FormInstance = InstanceType<typeof ElForm>;
  const loginFormRef = ref < FormInstance > ();
  const name = ref(proxy.$t("login.usernameRequired"));
  const loginRules = reactive({
    username: [{ required: true, message: name, trigger: "blur" }],
    password: [{ required: true, message: proxy.$t("errmsg.inputRequired", { cont: proxy.$t("login.password") }), trigger: "blur" }]
  });
	
  let language = ref(true);
  let langBool = computed(() => {
    return globalStore.language;
  });
  language.value = langBool.value === "zh";

  const loading = ref(false);
  const loginForm = reactive < Login.ReqLoginForm > ({
    username: "",
    password: ""
  });

  // login
  const login = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.validate(async valid => {
      if (!valid) return;
      loading.value = true;
      try {
        // 1.执行登录接口
        let { data, code, message } = await loginApi({ ...loginForm, password: loginForm.password });

        //登录验证错误
        if (code && code == ResultEnum.LOGINERROR) {
          ElMessage.error(message);
          return Promise.reject(data);
        }
        //  data = {
        //   username:'Krasnovidova Anastasiya',
        //   access_token : "bqddxxwqmfncffacvbpkuxvwvqrhln",
        //   id:0
        // }


        // if (data.code && data.code !== ResultEnum.SUCCESS) {
        //     ElMessage.error(data.message);
        //     return Promise.reject(data);
        //   }
		if(data?.merak_custom_settings?.userSetMsg){
			const differences = diffObj(globalStore.$state, data.merak_custom_settings.userSetMsg);
			console.log(globalStore.$state)
			console.log(data.merak_custom_settings.userSetMsg)
			if(differences.length > 0){
				globalStore.$state = data?.merak_custom_settings?.userSetMsg;
				
				if(isSafari.value){
					
				} else {
					window.location.href=window.location.href
				}
				
			}
		}
		if(data?.merak_custom_settings.tabsMenuList){
			tabsStore.setTabs(data.merak_custom_settings.tabsMenuList)
		} else {
			tabsStore.setTabs([]);
			keepAliveStore.setKeepAliveName([]);
		}
        userStore.setUser(data);
  console.log(data)
        // 2.添加动态路由
        await initDynamicRouter();


        //获取初始化组织架构tree
        await getAlltree();//初始化组织架构


        // 4.跳转到首页
        router.push(HOME_URL);
        // ElNotification({
        //   title: getTimeState(),
        //   message: "欢迎登录 Geeker-Admin",
        //   type: "success",
        //   duration: 3000
        // });
      } finally {
        loading.value = false;
      }
    });
  };
	const diffObj =(obj1, obj2)=> {
	  return Object.keys(obj1).concat(Object.keys(obj2))
		.filter(key => obj1[key] !== obj2[key]);
	}
  // resetForm
  const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.resetFields();
  };

  onMounted(() => {
    // 监听 enter 事件（调用登录）
    document.onkeydown = (e: KeyboardEvent) => {
      e = (window.event as KeyboardEvent) || e;
      if (e.code === "Enter" || e.code === "enter" || e.code === "NumpadEnter") {
        if (loading.value) return;
        login(loginFormRef.value);
      }
    };
  });

  const langChange = e => {
    // true zhCN false RU
    let lang = e ? "zh" : "ru";
    //i18n.locale.value = lang;
    globalStore.setGlobalState("language", lang as LanguageType);
    loginFormRef.value?.resetFields();
	window.location.href=window.location.href
  };
</script>

<style scoped lang="scss">
  @import "../index.scss";
</style>